/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package fr.unice.miage.projetjava.managers;

import fr.unice.miage.projetjava.entities.Users;
import fr.unice.miage.projetjava.*;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 * Session Bean gerant Users
 * @author Olivier
 */
@Stateless
public class GestionnaireDUserBean implements GestionnaireDUserLocal {
    @PersistenceContext
    private EntityManager em;

    public void persist(Object object) {
        em.persist(object);
    }
    
    // Add business logic below. (Right-click in editor and choose
    // "EJB Methods > Add Business Method" or "Web Service > Add Operation")

    public Users createUser(String fn, String ln, String  login, String pwd, String add1, String add2, String pc, String mail)
    {
        Users user = new Users();
        user.setFirstName(fn);
        user.setLastName(ln);
        user.setLogin(login);
        user.setPassword(pwd);
        user.setAddress1(add1);
        user.setAddress2(add2);
        user.setPostalCode(pc);
        user.setEmail(mail);
        em.persist(user);
        return user;
    }

    public void deleteUser(int id) {
        Users user = em.find(Users.class, id);
        em.remove(user);
    }

    public List<Users> listeUser()
    {
        Query query = em.createQuery("SELECT u FROM Users u");
        return query.getResultList();
    }

    public Users verifyUser(String login, String pwd)
    {
        try
        {
            Query query = em.createQuery("SELECT u FROM Users u WHERE u.login='"+login+"' AND u.password='"+pwd+"'");
            return (Users) query.getSingleResult();
        } catch (NoResultException e) {
            return null;
        }
    }

    public boolean verifyUserBool(String login, String pwd)
    {
        try
        {
            Query query = em.createQuery("SELECT u FROM Users u WHERE u.login='"+login+"' AND u.password='"+pwd+"'");
            if(query.getSingleResult().equals(null))
            {
                return true;
            }
            return false;
        } catch (NoResultException e) {
            return false;
        }
    }

    public void initUser()
    {
        createUser("Robert", "Lecuq", "bebere", "tarte", "", "", "", "");
        createUser("Eugene", "Moncuq", "gegene", "quiche", "", "", "", "");
        createUser("Michel", "Buffa", "mbuffa", "mbuffa", "", "", "", "");
        createUser("Admin", "Admin", "admin", "admin", "", "", "", "");
    }
    
}
